<template>
  <NavBar title="题库" color="#fff" colorText="#333" brg="#f8f8f8">
  <view class="question-bank-container">
    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 加载状态 -->
      <view v-if="loading && questions.length === 0" class="loading-container">
        <text class="loading-text">正在加载题目...</text>
      </view>

      <!-- 瀑布流容器 -->
      <view v-else class="waterfall-container">
        <!-- 左列 -->
        <view class="waterfall-column">
          <view class="question-card" v-for="(item, index) in leftColumnQuestions" :key="'left-' + item.id" @click="openQuestion(item)">
            <view class="question-type-label" :class="getTypeClass(item.qu_type)">{{ item.qu_type }}</view>
            <view class="question-content">
              <!-- 题目标题 -->
              <text class="question-text">{{ item.question }}</text>
              <!-- 题目图片 -->
              <view v-if="item.question_img && item.question_img !== ''" class="question-image-container">
                <image :src="item.question_img" mode="aspectFit" class="question-image" @error="onImageError" />
              </view>
              <!-- 题目选项 -->
              <view v-if="item.options && Object.keys(item.options).length > 0" class="question-options">
                <text class="options-label">选项</text>
                <text class="option-item" v-for="(option, key) in item.options" :key="key">
                  {{ key }}. {{ option }}
                </text>
              </view>
              <!-- 正确答案 -->
              <view class="correct-answer">
                <text class="answer-label">正确答案：</text>
                <text class="answer-text" v-for="(answer, key) in item.answer" :key="key">
                  {{ key }}. {{ answer }}
                </text>
              </view>
            </view>
          </view>
        </view>

        <!-- 右列 -->
        <view class="waterfall-column">
          <view class="question-card" v-for="(item, index) in rightColumnQuestions" :key="'right-' + item.id" @click="openQuestion(item)">
            <view class="question-type-label" :class="getTypeClass(item.qu_type)">{{ item.qu_type }}</view>
            <view class="question-content">
              <!-- 题目标题 -->
              <text class="question-text">{{ item.question }}</text>
              <!-- 题目图片 -->
              <view v-if="item.question_img && item.question_img !== ''" class="question-image-container">
                <image :src="item.question_img" mode="aspectFit" class="question-image" @error="onImageError" />
              </view>
              <!-- 题目选项 -->
              <view v-if="item.options && Object.keys(item.options).length > 0" class="question-options">
                <text class="options-label">选项</text>
                <text class="option-item" v-for="(option, key) in item.options" :key="key">
                  {{ key }}. {{ option }}
                </text>
              </view>
              <!-- 正确答案 -->
              <view class="correct-answer">
                <text class="answer-label">正确答案：</text>
                <text class="answer-text" v-for="(answer, key) in item.answer" :key="key">
                  {{ key }}. {{ answer }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore && !loading" class="load-more" @click="loadMoreQuestions">
        <text class="load-more-text">点击加载更多</text>
      </view>

      <!-- 底部加载状态 -->
      <view v-if="loading && questions.length > 0" class="bottom-loading">
        <text class="loading-text">正在加载更多...</text>
      </view>

      <!-- 没有更多数据 -->
      <view v-if="!hasMore && questions.length > 0" class="no-more">
        <text class="no-more-text">没有更多题目了</text>
      </view>
    </view>
  </view>
  </NavBar>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { BANK_API } from '../../config/api.js'

// 响应式数据
const questions = ref([]) // 所有题目数据
const leftColumnQuestions = ref([]) // 左列题目
const rightColumnQuestions = ref([]) // 右列题目
const loading = ref(false) // 加载状态
const hasMore = ref(true) // 是否还有更多数据
const currentPage = ref(1) // 当前页数

// 页面加载
onMounted(() => {
  console.log('题库页面已加载')
  loadQuestions()
})



// 加载题目数据
const loadQuestions = async () => {
  if (loading.value) return

  loading.value = true

  try {
    const response = await uni.request({
      url: `${BANK_API.QUESTIONS}?type=bank&page=${currentPage.value}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }
    })

    console.log('题库API响应:', response)

    if (response.statusCode === 200 && response.data.code === 200) {
      const newQuestions = response.data.data.questions || []

      // 添加新题目到现有列表
      questions.value.push(...newQuestions)

      // 更新分页信息
      hasMore.value = response.data.data.has_more || false
      currentPage.value += 1

      // 重新分配瀑布流布局
      redistributeQuestions()

      console.log('题目加载成功，当前题目数量:', questions.value.length)
    } else {
      console.error('题库API返回错误:', response.data)
      uni.showToast({
        title: '加载题目失败',
        icon: 'none',
        duration: 2000
      })
    }
  } catch (error) {
    console.error('加载题目失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
      duration: 2000
    })
  } finally {
    loading.value = false
  }
}

// 重新分配瀑布流布局
const redistributeQuestions = () => {
  leftColumnQuestions.value = []
  rightColumnQuestions.value = []

  // 为每个题目计算高度并分配到较短的列
  questions.value.forEach((question) => {
    const questionHeight = calculateQuestionHeight(question)

    // 计算当前两列的总高度
    const leftHeight = leftColumnQuestions.value.reduce((sum, q) => sum + calculateQuestionHeight(q), 0)
    const rightHeight = rightColumnQuestions.value.reduce((sum, q) => sum + calculateQuestionHeight(q), 0)

    // 将题目分配到高度较小的列
    if (leftHeight <= rightHeight) {
      leftColumnQuestions.value.push(question)
    } else {
      rightColumnQuestions.value.push(question)
    }
  })
}

// 计算题目高度（基于内容复杂度）
const calculateQuestionHeight = (question: any) => {
  let height = 120 // 基础高度（标签 + 内边距）

  // 题目文本高度（根据文本长度估算）
  const textLength = question.question ? question.question.length : 0
  height += Math.ceil(textLength / 15) * 30 // 每15个字符一行

  // 选项高度
  const optionsCount = question.options ? Object.keys(question.options).length : 0
  height += optionsCount * 30

  // 答案高度
  const answersCount = question.answer ? Object.keys(question.answer).length : 0
  height += answersCount * 25 + 30 // 答案标签高度

  // 图片高度
  if (question.question_img && question.question_img !== '') {
    height += 200 // 图片高度
  }

  // 间距
  height += 20 // 底部间距

  return height
}

// 加载更多题目
const loadMoreQuestions = () => {
  if (!hasMore.value || loading.value) return
  loadQuestions()
}

// 获取题目类型对应的CSS类
const getTypeClass = (type: string) => {
  switch(type) {
    case '单选题':
      return 'single-choice'
    case '多选题':
      return 'multiple-choice'
    case '判断题':
      return 'true-false'
    default:
      return 'default-choice'
  }
}

// 图片加载错误处理
const onImageError = (e: any) => {
  console.error('图片加载失败:', e)
}

// 打开题目详情
const openQuestion = (question: any) => {
  console.log('打开题目:', question)

  uni.showToast({
    title: `查看${question.qu_type}`,
    icon: 'none',
    duration: 1500
  })

  // 这里可以跳转到题目详情页面
  // uni.navigateTo({ url: `/pages/question-detail/question-detail?id=${question.id}` })
}

// 页面选项
const onReachBottom = () => {
  console.log('滚动到底部')
  if (hasMore.value && !loading.value) {
    loadQuestions()
  }
}

// 导出页面生命周期函数
defineExpose({
  onReachBottom
})
</script>

<style scoped>
/* 题库页面样式 */
.question-bank-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient( 180deg, #C2DDFF 0%, #FFFFFF 100%);
  border-radius: 0rpx 0rpx 0rpx 0rpx;
  padding-top: 160rpx;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx 10rpx;
  background: transparent;
  position: sticky;
  top: 0;
  z-index: 100;
}

.status-time {
  font-size: 34rpx;
  font-weight: 600;
  color: #1A1A1A;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.status-icon {
  font-size: 24rpx;
  color: #1A1A1A;
  opacity: 0.8;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx;
  background: transparent;
  position: sticky;
  top: 80rpx;
  z-index: 99;
}

.nav-left {
  display: flex;
  align-items: center;
}

.back-arrow {
  font-size: 40rpx;
  color: #333;
  font-weight: bold;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #1A1A1A;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.nav-right {
  display: flex;
  align-items: center;
}

.search-box {
  background: #f0f0f0;
  border-radius: 20rpx;
  padding: 12rpx 24rpx;
  min-width: 120rpx;
  text-align: center;
  transition: all 0.3s ease;
  cursor: pointer;
}

.search-box:active {
  background: #e0e0e0;
  transform: scale(0.95);
}

.search-placeholder {
  font-size: 28rpx;
  color: #999;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  padding: 20rpx 30rpx 40rpx;
  width: 100%;
  box-sizing: border-box;
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.bottom-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

/* 加载更多 */
.load-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  cursor: pointer;
}

.load-more-text {
  font-size: 28rpx;
  color: #007AFF;
}

/* 没有更多数据 */
.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.no-more-text {
  font-size: 24rpx;
  color: #999;
}

/* 瀑布流容器 */
.waterfall-container {
  display: flex;
  gap: 20rpx;
  align-items: flex-start;
  width: 100%;
  box-sizing: border-box;
}

/* 瀑布流列 */
.waterfall-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  width: calc(50% - 10rpx);
  box-sizing: border-box;
}

/* 题目卡片 */
.question-card {
  background: white;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  width: 100%;
  min-height: auto;
  margin-bottom: 0;
  box-sizing: border-box;
  /* 确保卡片不会重叠 */
  display: block;
}

.question-card:active {
  transform: translateY(2rpx);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.12);
}

/* 题目类型标签 */
.question-type-label {
  position: absolute;
  top: 16rpx;
  left: 16rpx;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  font-size: 20rpx;
  font-weight: 600;
  color: white;
  z-index: 1;
}

.single-choice {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.multiple-choice {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.true-false {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.default-choice {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

/* 题目内容 */
.question-content {
  margin-top: 40rpx;
}

/* 题目图片 */
.question-image-container {
  width: 100%;
  margin-bottom: 16rpx;
}

.question-image {
  width: 100%;
  max-height: 200rpx;
  border-radius: 8rpx;
}

.question-text {
  font-size: 26rpx;
  color: #333;
  line-height: 1.4;
  display: block;
  margin-bottom: 16rpx;
  font-weight: 500;
}

/* 题目选项 */
.question-options {
  margin-bottom: 16rpx;
}

.options-label {
  font-size: 22rpx;
  color: #666;
  font-weight: 600;
  display: block;
  margin-bottom: 8rpx;
}

.option-item {
  font-size: 24rpx;
  color: #555;
  line-height: 1.5;
  display: block;
  margin-bottom: 8rpx;
  padding: 8rpx 12rpx;
  background: #f8f9fa;
  border-radius: 6rpx;
}

/* 正确答案 */
.correct-answer {
  margin-top: 16rpx;
  padding: 12rpx;
  background: #f0f9ff;
  border-radius: 8rpx;
  border-left: 4rpx solid #007AFF;
}

.answer-label {
  font-size: 22rpx;
  color: #007AFF;
  font-weight: 600;
  display: block;
  margin-bottom: 8rpx;
}

.answer-text {
  font-size: 22rpx;
  color: #007AFF;
  font-weight: 600;
  display: block;
  margin-bottom: 4rpx;
}



/* 底部指示条 */
.bottom-indicator {
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 120rpx;
  height: 8rpx;
  background: #000;
  border-radius: 4rpx;
  margin-bottom: 10rpx;
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .waterfall-container {
    flex-direction: column;
    gap: 16rpx;
  }
  
  .waterfall-column {
    width: 100%;
    gap: 16rpx;
  }
  
  .question-card {
    padding: 16rpx;
  }
  
  .question-text {
    font-size: 24rpx;
  }
  
  .point-item,
  .step-item {
    font-size: 20rpx;
  }
}

/* 动画效果 */
.question-card {
  animation: fadeInUp 0.6s ease-out;
}

.question-card:nth-child(odd) {
  animation-delay: 0.1s;
}

.question-card:nth-child(even) {
  animation-delay: 0.2s;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
